using System;
using System.Threading.Tasks;
using AutoMapper;
using Terra.Core.Common.ApiResponse;
using Terra.Core.Common.Models.Pagination;
using Terra.Data.Entities.Logging;
using Terra.Data.Repository.Logging;
using Terra.Data.UnitOfWork;
using Terra.Service.Common.Base;
using Terra.Service.Logging.DTOs;
using Terra.Service.Logging.Interfaces;

namespace Terra.Service.Logging.Implementations;

/// <summary>
/// 登录日志服务实现
/// </summary>
public class LoginLogService : AppServiceBase, ILoginLogService
{
    private readonly ILoginLogRepository _loginLogRepository;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="unitOfWork">工作单元</param>
    /// <param name="mapper">对象映射器</param>
    /// <param name="loginLogRepository">登录日志仓储</param>
    public LoginLogService(
        IUnitOfWork unitOfWork,
        IMapper mapper,
        ILoginLogRepository loginLogRepository) : base(unitOfWork, mapper)
    {
        _loginLogRepository = loginLogRepository;
    }

    /// <inheritdoc />
    public async Task<ApiResponse<Guid>> LogAsync(CreateLoginLogRequest request)
    {
        try
        {
            var log = Mapper.Map<LoginLog>(request);
            log = await _loginLogRepository.InsertAsync(log);
            return ApiResponse<Guid>.Success(log.Id, "登录日志记录成功");
        }
        catch (Exception ex)
        {
            return ApiResponse<Guid>.Error("LOG001", $"记录登录日志失败: {ex.Message}");
        }
    }

    /// <inheritdoc />
    public async Task<ApiResponse<PagedList<LoginLogDto>>> GetPagedListAsync(LoginLogPagedRequest request)
    {
        try
        {
            var result = await _loginLogRepository.GetPagedListAsync(
                request.UserName,
                request.Status,
                request.StartTime,
                request.EndTime,
                request.PageIndex,
                request.PageSize);

            return ApiResponse<PagedList<LoginLogDto>>.Success(
                new PagedList<LoginLogDto>(
                    Mapper.Map<List<LoginLogDto>>(result.Items),
                    result.TotalCount,
                    result.PageIndex,
                    result.PageSize),
                "获取登录日志成功");
        }
        catch (Exception ex)
        {
            return ApiResponse<PagedList<LoginLogDto>>.Error("LOG002", $"获取登录日志失败: {ex.Message}");
        }
    }

    /// <inheritdoc />
    public async Task<ApiResponse<int>> CleanAsync(DateTime beforeTime)
    {
        try
        {
            var count = await _loginLogRepository.CleanAsync(beforeTime);
            return ApiResponse<int>.Success(count, $"成功清理 {count} 条登录日志");
        }
        catch (Exception ex)
        {
            return ApiResponse<int>.Error("LOG003", $"清理登录日志失败: {ex.Message}");
        }
    }
}